<template>
  <div class="app-container">
    <div class="body-div">
      <el-button type="primary" style="float: right" @click="back()"
        >返回</el-button
      >
      <div style="padding: 10px">
        <div style="display: flex; margin-bottom: 10px">
          <div class="shuxian"></div>
          <span class="headtitle">基本信息</span>
        </div>
        <el-descriptions title="" class="custom-descriptions" :column="2">
          <el-descriptions-item label="项目名称："
            >{{ formData.projectName }}
          </el-descriptions-item>
          <el-descriptions-item label="项目编号：">
            {{ formData.projectCode }}</el-descriptions-item
          >
          <el-descriptions-item label="客户名称：">
            {{ formData.customerName }}</el-descriptions-item
          >
          <el-descriptions-item label="创建时间：">{{
            formData.createTime
          }}</el-descriptions-item>
        </el-descriptions>

        <el-row style="margin-top: 10px">
          <el-col :span="23">
            <div style="display: flex; margin-top: 10px; width: 100%">
              <div class="shuxian"></div>
              <span class="headtitle">设计输入条件</span>
              <el-button
                type="primary"
                style="margin-left: 20px"
                v-hasPermi="['project:projectData:addFurnace']"
                @click="
                  showfurnace = true;
                  furnaceFormData.furnaceAddName = '';
                  dialogTitle = '添加反应炉';
                "
                >添加反应炉</el-button
              >
              <el-button
                type="primary"
                style="margin-left: 20px"
                @click="handleFurnace"
                v-hasPermi="['project:projectData:handleFurnace']"
                >处理其他反应炉</el-button
              >
            </div>
          </el-col>
          <el-col :span="1">
            <el-button
              type="primary"
              style="float: right"
              v-hasPermi="['project:projectData:projectEdit']"
              @click="edit()"
              >输入条件</el-button
            >
          </el-col>
        </el-row>

        <div style="margin-top: 15px">
          <el-tabs v-model="furnaceName" @tab-click="furnaceClick" type="card">
            <el-tab-pane
              v-for="(tab, index) in furnaceList"
              :key="index"
              :label="tab.furnaceName"
              :name="tab.projectFurnaceId"
            >
            </el-tab-pane>
          </el-tabs>
          <DynamicTabs
            :tabs="tabsData"
            @update-active-name="handleActiveNameUpdate"
          />
        </div>
        <div style="margin-top: 15px" v-if="false">
          <div style="display: flex; margin-bottom: 10px">
            <div class="shuxian"></div>
            <span class="headtitle">设计输入条件</span>
          </div>
          <div class="app-bottom">添加或者编辑输入条件！</div>
        </div>
        <div style="margin-top: 15px">
          <div style="display: flex; margin-bottom: 10px">
            <div class="shuxian"></div>
            <span class="headtitle">设计方案</span>
            <el-button
              type="primary"
              style="margin-left: 20px"
              @click="designList()"
              >历史方案列表</el-button
            >
          </div>

          <div class="app-bottom">
            <div
              class="design-center"
              v-for="(item, index) in allDesign"
              :key="index"
            >
              <el-icon style="color: #4351d1; font-size: 25px"
                ><Document
              /></el-icon>
              <span style="margin-left: 10px">
                {{ item[1] }}
              </span>
              <el-button
                :icon="Search"
                circle
                style="margin-left: 10px"
                @click="computedDetail(item[0], item[1], item[2], item[3])"
              />
              <el-button
                type="danger"
                :icon="Delete"
                circle
                style="margin-left: 10px"
                v-hasPermi="['project:projectData:removeDesign']"
                @click="deleteDetail(item[0], item[1])"
              />
            </div>
            添加设计方案！
            <el-button
              type="primary"
              @click="design()"
              v-hasPermi="['project:projectData:addDesign']"
              >添加设计方案</el-button
            >
          </div>
        </div>
      </div>
      <el-dialog
        v-model="showDialogBefore"
        title="前置计算条件输入"
        width="80%"
        :close-on-click-modal="false"
      >
        <!-- 表单内容 -->
        <el-form
          :model="formDialogBefore"
          :rules="rulesDialogBefore"
          ref="formRefDialogBefore"
          label-width="250px"
          :inline="true"
        >
          <el-form-item label="烟气流向：" prop="smokeFlow">
            <el-select
              style="width: 200px"
              v-model="formDialogBefore.smokeFlow"
              placeholder="请选择烟气流向"
            >
              <el-option label="垂直方向" value="0" />
              <el-option label="水平方向" value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="烟气流速相对偏差：" prop="smokeRateOffset">
            <el-input
              style="width: 200px"
              v-model="formDialogBefore.smokeRateOffset"
            ></el-input>
          </el-form-item>
          <el-form-item label="烟气温度偏差：" prop="smokeTemperatureOffset">
            <el-input
              style="width: 200px"
              v-model="formDialogBefore.smokeTemperatureOffset"
            ></el-input>
          </el-form-item>
          <el-form-item label="氨氮摩尔比偏差：" prop="nh3NoxRatioOffset">
            <el-input
              style="width: 200px"
              v-model="formDialogBefore.nh3NoxRatioOffset"
            ></el-input>
          </el-form-item>
          <el-form-item label="催化剂类型号：" prop="categoryName">
            <el-select
              style="width: 200px"
              v-model="formDialogBefore.categoryName"
              @change="changeCategory"
              ><el-option
                v-for="item in categoryNameSource"
                :key="item.projectName"
                :label="item.projectName"
                :value="item.projectName"
              >
              </el-option
            ></el-select>
          </el-form-item>
          <el-form-item label="催化剂使用年限：" prop="year">
            <el-select style="width: 200px" v-model="formDialogBefore.year"
              ><el-option
                v-for="item in yearSource"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              >
              </el-option
            ></el-select>
          </el-form-item>
          <el-form-item label="催化剂化学寿命(h)：" prop="lifetime">
            <el-input
              style="width: 200px"
              v-model="formDialogBefore.lifetime"
            ></el-input>
          </el-form-item>
          <el-form-item label="出口氮氧化物排放值：" prop="outNox">
            <el-input style="width: 370px" v-model="formDialogBefore.outNox">
              <template #append>mg/Nm3 dry @3% 02</template></el-input
            >
          </el-form-item>
          <el-form-item label="每台机组反应器数(个)：" prop="reactorCount">
            <el-input
              style="width: 200px"
              v-model="formDialogBefore.reactorCount"
            ></el-input>
          </el-form-item>

          <el-form-item label="反应器尺寸L(mm)：" prop="reactorL">
            <el-input v-model="formDialogBefore.reactorL" style="width: 200px">
              <template #prepend>L:</template></el-input
            >
          </el-form-item>
          <el-form-item label="反应器尺寸W(mm)：" prop="reactorW">
            <el-input v-model="formDialogBefore.reactorW" style="width: 200px">
              <template #prepend>W:</template></el-input
            >
          </el-form-item>
          <el-form-item label="氨氮摩尔比NH3/NOX：" prop="outNh3Nox">
            <el-input
              style="width: 200px"
              v-model="formDialogBefore.outNh3Nox"
            ></el-input>
          </el-form-item>
          <el-form-item label="出口氨逃逸Nh3：" prop="outNh3">
            <el-input style="width: 370px" v-model="formDialogBefore.outNh3">
              <template #append>mg/Nm3 dry @3% 02</template></el-input
            >
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="handleSaveBefore">保存</el-button>
            <el-button @click="showDialogBefore = false">取消</el-button>
          </span>
        </template>
      </el-dialog>
      <el-dialog
        v-model="showDialog"
        title="转换通用单位数据"
        width="40%"
        @close="handleDialogClose"
        :close-on-click-modal="false"
        :index="reload"
      >
        <el-tabs v-model="activeName" @tab-click="tabClick">
          <el-tab-pane
            v-for="(tab, index) in tabsData"
            :key="index"
            :label="tab.label"
            :name="tab.name"
          >
          </el-tab-pane>
        </el-tabs>
        <el-form
          :model="formDialog"
          :rules="rulesDialog"
          ref="formRefDialog"
          label-width="100px"
          style="margin-top: 10px"
        >
          <el-form-item label="烟气流量：" prop="quantityFlow">
            <el-input v-model="formDialog.quantityFlow"></el-input>
          </el-form-item>
          <el-form-item label="温度：" prop="temperature">
            <el-input v-model="formDialog.temperature"></el-input>
          </el-form-item>
          <el-form-item label="烟气压力：" prop="pressure">
            <el-input v-model="formDialog.pressure"></el-input>
          </el-form-item>
          <el-form-item label="氮氧化物：" prop="nox">
            <el-input v-model="formDialog.nox"></el-input>
          </el-form-item>
          <el-form-item label="二氧化氮：" prop="no2" v-if="false">
            <el-input v-model="formDialog.no2"></el-input>
          </el-form-item>
          <el-form-item label="氧含量：" prop="o">
            <el-input v-model="formDialog.o"></el-input>
          </el-form-item>
          <el-form-item label="水蒸汽：" prop="h2o">
            <el-input v-model="formDialog.h2o"></el-input>
          </el-form-item>
          <el-form-item label="一氧化碳：" prop="co">
            <el-input v-model="formDialog.co"></el-input>
          </el-form-item>
          <el-form-item label="二氧化碳：" prop="co2">
            <el-input v-model="formDialog.co2"></el-input>
          </el-form-item>
          <el-form-item label="二氧化硫：" prop="so2">
            <el-input v-model="formDialog.so2"></el-input>
          </el-form-item>
          <el-form-item label="三氧化硫：" prop="so3">
            <el-input v-model="formDialog.so3"></el-input>
          </el-form-item>
          <el-form-item label="颗粒物：" prop="pm">
            <el-input v-model="formDialog.pm"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="handleSave">保存</el-button>
            <el-button @click="showDialog = false">取消</el-button>
          </span>
        </template>
      </el-dialog>
      <el-dialog
        v-model="showfurnace"
        :title="dialogTitle"
        width="40%"
        :close-on-click-modal="false"
      >
        <el-form
          :model="furnaceFormData"
          :rules="rulesFurnaceFormData"
          ref="furnaceFormRef"
          label-width="120px"
        >
          <el-form-item label="反应炉名称：" prop="furnaceAddName">
            <el-input v-model="furnaceFormData.furnaceAddName"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="addFurnaceSave">保存</el-button>
            <el-button @click="showfurnace = false">取消</el-button>
          </span>
        </template>
      </el-dialog>
      <el-dialog
        v-model="showfurnaceHandle"
        title="处理反应炉"
        width="60%"
        :close-on-click-modal="false"
      >
        <el-table :data="furnaceData" border style="width: 100%">
          <el-table-column prop="furnaceName" label="反应炉名称" />
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <el-button
                size="small"
                @click="handleEdit(scope.$index, scope.row)"
              >
                修改
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="showfurnaceHandle = false"
              >确定</el-button
            >
            <el-button @click="showfurnaceHandle = false">取消</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import { useRoute } from "vue-router";
import http from "@/utils/ajaxUtils";
import request from "@/utils/request";
import { ElMessage, ElPopover, ElButton, ElMessageBox } from "element-plus";
import DynamicTabs from "@/components/MSTN/dynamicTabs.vue";
import { cloneDeep } from "lodash-es";
import { Search, Delete } from "@element-plus/icons-vue";
import { getDicts } from "@/api/system/dict/data";

const router = useRouter();
const route = useRoute();
const id = route.params.id;

const batchId = ref("");

const furnaceName = ref("默认");
const furnaceList = ref([]); //炉子列表
const furnaceOther = ref([]);
const showfurnace = ref(false); //炉子弹框显示
const furnaceFormData = ref({});
const furnaceFormRef = ref(null);
const rulesFurnaceFormData = {
  furnaceAddName: [
    { required: true, message: "请输入反应炉名称", trigger: "blur" },
  ],
};
function addFurnaceSave() {
  furnaceFormRef.value.validate((valid) => {
    if (valid) {
      request({
        url: "/system/project/edit/ProjectFurnace",
        method: "post",
        data: {
          projectFurnaceId: furnaceFormData.value.projectFurnaceId,
          furnaceName: furnaceFormData.value.furnaceAddName,
          projectId: id,
        },
      }).then((response) => {
        if (response.code == 200) {
          if (dialogTitle.value == "添加反应炉") {
            ElMessage.success("添加反应炉成功成功");
          } else {
            ElMessage.success("修改反应炉成功成功");
          }

          // furnaceList.value.push({
          //   furnaceName: furnaceFormData.value.furnaceAddName,
          // });
          tabsData.value = [];
          getList();
          furnaceFormData.value.furnaceAddName = "";
          showfurnace.value = false;
          showfurnaceHandle.value = false;
        }
      });
    }
  });
}

// 初始化activeName
const activeName = ref("额定工况");

const formData = ref({});

const formDataOther = ref([]);

const tabsData = ref([]);

const showDialog = ref(false); //弹框显示

const showDialogBefore = ref(false); //前置计算条件输入

const saveFormData = ref([]); // 最终存储的数据源

const projectConditionId = ref(""); //前置计算条件id

const reload = ref(0);

const allDesign = ref([]);

const furnaceData = ref([]); //表格数据

const requiredFields = [
  "quantityFlow",
  "temperature",
  "pressure",
  "nox",
  "no2",
  "o",
  "h2o",
  "co",
  "co2",
  "so2",
  "so3",
  "pm",
];

const dialogTitle = ref("添加反应炉");
const showfurnaceHandle = ref(false);

//催化剂使用年限
const yearSource = ref([]);

//前置条件计算数据源
const formDialogBefore = ref({});
const formRefDialogBefore = ref(null);
const rulesDialogBefore = {
  smokeFlow: [{ required: true, message: "请选择烟气流向", trigger: "blur" }],
  categoryName: [
    { required: true, message: "请输入催化剂类型号", trigger: "blur" },
  ],
  reactorCount: [
    { required: true, message: "请输入每台机组反应器数", trigger: "blur" },
  ],
  lifetime: [
    { required: true, message: "请输入催化剂化学寿命", trigger: "blur" },
  ],
  outNox: [
    { required: true, message: "请输入出口氮氧化物排放值", trigger: "blur" },
  ],
  smokeRateOffset: [
    { required: true, message: "请输入烟气流速相对偏差", trigger: "blur" },
  ],
  smokeTemperatureOffset: [
    { required: true, message: "请输入烟气温度偏差", trigger: "blur" },
  ],
  nh3NoxRatioOffset: [
    { required: true, message: "请输入氨氮摩尔比偏差", trigger: "blur" },
  ],
  outNh3Nox: [{ required: true, message: "请输入氨氮摩尔比", trigger: "blur" }],
  outNh3: [{ required: true, message: "请输入出口氨逃逸", trigger: "blur" }],
  reactorL: [{ required: true, message: "请输入反应器尺寸L", trigger: "blur" }],
  reactorW: [{ required: true, message: "请输入反应器尺寸W", trigger: "blur" }],
  year: [{ required: true, message: "请选择催化剂使用年限", trigger: "blur" }],
};

const tabValue = ref("1");

//全部数据源
const allBeforeData = ref([]);
// 定义定时器变量（用于清除）
let timer = null;

//组件回传值
const currentActiveName = ref("1");

//催化剂类型号数据源
const categoryNameSource = ref([]);

const handleActiveNameUpdate = (name) => {
  currentActiveName.value = name; // 接收子组件传递的值
};

function commonFilter() {
  for (let i = 0; i < allBeforeData.value.length; i++) {
    if (allBeforeData.value[i].conditionType == activeName.value) {
      formDialog.value.conditionType = allBeforeData.value[i].conditionType;
      formDialog.value.projectConditionId =
        allBeforeData.value[i].projectConditionId;
      allBeforeData.value[i] = cloneDeep(formDialog.value);
    }
  }
}

//弹框数据源
const formDialog = ref({
  projectName: "",
  temperature: "",
  pressure: "",
  nox: "",
  no2: "",
  o: "",
  h2o: "",
  co: "",
  co2: "",
  so2: "",
  so3: "",
  pm: "",
}); //弹框数据源

const formRefDialog = ref(null);
const rulesDialog = {
  quantityFlow: [
    { required: true, message: "请输入烟气流量", trigger: "blur" },
  ],
  temperature: [{ required: true, message: "请输入温度", trigger: "blur" }],
  pressure: [{ required: true, message: "请输入烟气压力", trigger: "blur" }],
  nox: [{ required: true, message: "请输入氮氧化物", trigger: "blur" }],
  no2: [{ required: true, message: "请输入二氧化氮", trigger: "blur" }],
  o: [{ required: true, message: "请输入氧含量", trigger: "blur" }],
  h2o: [{ required: true, message: "请输入水蒸气", trigger: "blur" }],
  co: [{ required: true, message: "请输入一氧化碳", trigger: "blur" }],
  co2: [{ required: true, message: "请输入二氧化碳", trigger: "blur" }],
  so2: [{ required: true, message: "请输入二氧化硫", trigger: "blur" }],
  so3: [{ required: true, message: "请输入三氧化硫", trigger: "blur" }],
  pm: [{ required: true, message: "请输入颗粒物", trigger: "blur" }],
};

//细节查看
function computedDetail(itemId, itemName, schemeComputeId, resultId) {
  if (resultId != null) {
    router.push(
      `/projects/projectData/designDetailProject/${id}/${itemId}/${schemeComputeId}`
    );
  } else {
    router.push(`/projects/projectData/makeProject/${id}/${itemId}`);
  }
}

function back() {
  router.push(`/projects/projectData`).then(() => {});
}

function furnaceClick(tab, event) {
  furnaceName.value = tab.props.name;
  tabsData.value = [];
  const furnaceOther = ref([]);
  for (let i = 0; i < formDataOther.value.length; i++) {
    if (formDataOther.value[i].projectFurnaceId == furnaceName.value) {
      furnaceOther.value = formDataOther.value[i].conditionList;
      break;
    }
  }
  for (let i = 0; i < furnaceOther.value.length; i++) {
    tabsData.value.push({
      label: furnaceOther.value[i].conditionType,
      name: furnaceOther.value[i].conditionType,
      content: furnaceOther.value[i],
    });
  }
}

function handleFurnace() {
  //获取反应炉数据
  request({
    url: "/system/project/selectMstnProjectFurnaceList/" + id,
    method: "get",
    params: {},
  }).then((response) => {
    if (response.code == 200) {
      furnaceData.value = response.data;
      showfurnaceHandle.value = true;
    }
  });
}

//修改
function handleEdit(index, row) {
  dialogTitle.value = "修改反应炉";
  furnaceFormData.value.furnaceAddName = row.furnaceName;
  furnaceFormData.value.projectFurnaceId = row.projectFurnaceId;
  furnaceFormData.value.projectId = row.projectId;
  showfurnace.value = true;
}

//删除
function handleDelete(index, row) {
  ElMessageBox.confirm("是否确认删除该反应炉？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      request({
        url: "/system/project/removeFurnace",
        method: "delete",
        data: {
          projectId: id,
          projectFurnaceId: row.projectFurnaceId,
        },
      }).then((response) => {
        if (response.code == 200) {
          ElMessage.success("删除成功");
          tabsData.value = [];
          getList();
          showfurnaceHandle.value = false;
        }
      });
    })
    .catch(() => {
      //取消操作
    });
}

function getList() {
  http.get("/system/project/" + id, {}).then((response) => {
    formData.value = response.data;
    formDataOther.value = response.data.furnaceList;
    furnaceList.value = response.data.furnaceList; //设置炉子列表
    furnaceName.value = response.data.furnaceList[0].projectFurnaceId; //设置炉子名称
    if (
      response.data.furnaceList.length > 0 &&
      response.data.furnaceList[0].conditionList &&
      response.data.furnaceList[0].conditionList.length > 0
    ) {
      //取出所有的tabs
      for (
        let i = 0;
        i < response.data.furnaceList[0].conditionList.length;
        i++
      ) {
        tabsData.value.push({
          label: response.data.furnaceList[0].conditionList[i].conditionType,
          name: response.data.furnaceList[0].conditionList[i].conditionType,
          content: response.data.furnaceList[0].conditionList[i],
        });
      }
    }
    console.log("tabsData", tabsData.value);
  });
}

function edit() {
  router
    .push(`/projects/projectData/editProject/${id}/${furnaceName.value}`)
    .then(() => {});
}

//转换单位修改
function changeCategory(value) {
  getDicts("mstn_catalysts_" + value).then((response) => {
    yearSource.value = response.data;
    formDialogBefore.value.year = "";
  });
}

//前置条件输入
function design() {
  formDialog.value = {};
  showDialogBefore.value = true;
}

//前置条件输入保存按钮
function handleSaveBefore() {
  formRefDialogBefore.value.validate((valid) => {
    if (valid) {
      formDialogBefore.value.projectId = id;
      formDialogBefore.value.projectStatus = formDialog.value.projectStatus;
      showDialogBefore.value = false;
      //把数据转换为标准数据
      activeName.value = tabsData.value[0].label;
      changeCommonData(activeName.value);
      // test();
      showDialog.value = true;
    }
  });
}

function tabClick(tab, event) {
  //先赋值然后再找到之前的值
  commonFilter();
  for (let i = 0; i < allBeforeData.value.length; i++) {
    if (allBeforeData.value[i].conditionType == tab.props.name) {
      formDialog.value = cloneDeep(allBeforeData.value[i]);
    }
  }
  // test();
  tabValue.value = tab.props.name;
  reload.value += 1;
  changeCommonData(tab.props.name);
}

function changeCommonData(value) {
  //拿到数据
  const index = value
    ? tabsData.value.findIndex((item) => item.label === value)
    : 0;
  const beforeGenerate = tabsData.value[index].content;
  formDialog.value.temperature = beforeGenerate.temperature;
  formDialog.value.quantityFlow = beforeGenerate.quantityFlow;
  formDialog.value.pressure = beforeGenerate.pressure;
  formDialog.value.pm = beforeGenerate.pm ? beforeGenerate.pm : 0;
  formDialog.value.projectFurnaceId = beforeGenerate.projectFurnaceId;
  formDialog.value.conditionType = beforeGenerate.conditionType;

  //开始转换   所有的湿基转换不参与计算
  //h2o  1-mol%  2-kg/h  3-Nm3/h
  if (beforeGenerate.h2oUnit != "" && beforeGenerate.quantityFlow != "") {
    // if (beforeGenerate.h2oUnit == "1") {
    //   //mol% 转为Nm3/h
    //   formDialog.value.h2o = (
    //     (beforeGenerate.h2o * beforeGenerate.quantityFlow) /
    //     100
    //   ).toFixed(2);
    // }
    if (beforeGenerate.h2oUnit == "3") {
      //Nm3/h 转为mol%
      formDialog.value.h2o =
        (beforeGenerate.h2o * 100) / beforeGenerate.quantityFlow.toFixed(2);
    } else if (beforeGenerate.h2oUnit == "2") {
      //kg/h 转为Nm3/h
      formDialog.value.h2o = ((beforeGenerate.h2o / 18) * 22.4).toFixed(2);
      //Nm3/h 转为mol%
      formDialog.value.no2 =
        (beforeGenerate.no2 * 100) / beforeGenerate.quantityFlow.toFixed(2);
    } else {
      formDialog.value.h2o = beforeGenerate.h2o;
    }
  }

  //先把水的单位从标准单位转换为mol%
  // const driver = (formDialog.value.h2o / beforeGenerate.quantityFlow).toFixed(
  //   2
  // );
  //formDialog.value.h2o = driver;
  const driver = formDialog.value.h2o;

  //nox   1-Nm3/h   2-kg/h  3-mg/Nm3
     //nox 统一变成 mg/Nm3
  if (beforeGenerate.noxUnit == "2") {
    formDialog.value.nox = ((beforeGenerate.nox / 46) * 22.4).toFixed(2);
    formDialog.value.nox = (
      (formDialog.value.nox * 1000000 * 46) /
      (22.4 * beforeGenerate.quantityFlow)
    ).toFixed(0);
  } else if (beforeGenerate.noxUnit == "3") {
    formDialog.value.nox = beforeGenerate.nox;
  } else {
    formDialog.value.nox = (
      (formDialog.value.nox * 1000000 * 46) /
      (22.4 * beforeGenerate.quantityFlow)
    ).toFixed(0);
  }

  //干基转湿基
  if (beforeGenerate.noxType == "1") {
    formDialog.value.nox = (formDialog.value.nox * (1 - driver / 100)).toFixed(
      2
    );
  }

  //so2  1-mol%  2-Nm3/h   3-kg/h  4-mg/Nm3
  if (beforeGenerate.so2Unit != "" && beforeGenerate.quantityFlow != "") {
    if (beforeGenerate.so2Unit == "1") {
      formDialog.value.so2 = (
        (beforeGenerate.so2 * beforeGenerate.quantityFlow) /
        100
      ).toFixed(2);
    } else if (beforeGenerate.so2Unit == "3") {
      //kg/h 转为Nm3/h
      formDialog.value.so2 = ((beforeGenerate.so2 / 64) * 22.4).toFixed(2);
    } else if (beforeGenerate.so2Unit == "4") {
      //mg/Nm3 转为Nm3/h
      formDialog.value.so2 = (
        ((beforeGenerate.so2 * beforeGenerate.quantityFlow) / 1000000 / 64) *
        22.4
      ).toFixed(2);
    } else {
      formDialog.value.so2 = beforeGenerate.so2;
    }
  }
  //干基转湿基
  if (beforeGenerate.so2Type == "1") {
    formDialog.value.so2 = (formDialog.value.so2 * (1 - driver / 100)).toFixed(
      2
    );
  }

  //so3  1-mol%  2-mg/Nm3  3-kg/h  4-Nm3/h
  if (beforeGenerate.so3Unit != "" && beforeGenerate.quantityFlow != "") {
    if (beforeGenerate.so3Unit == "1") {
      formDialog.value.so3 = (
        (beforeGenerate.so3 * beforeGenerate.quantityFlow) /
        100
      ).toFixed(2);
    } else if (beforeGenerate.so3Unit == "3") {
      //kg/h 转为Nm3/h
      formDialog.value.so3 = ((beforeGenerate.so2 / 80) * 22.4).toFixed(2);
    } else if (beforeGenerate.so3Unit == "2") {
      formDialog.value.so3 = (
        ((beforeGenerate.so3 * beforeGenerate.quantityFlow) / 1000000 / 80) *
        22.4
      ).toFixed(2);
    } else {
      formDialog.value.so3 = beforeGenerate.so3 ? beforeGenerate.so3 : "0";
    }
  }
  //干基转湿基
  if (beforeGenerate.so3Type == "1") {
    formDialog.value.so3 = (formDialog.value.so3 * (1 - driver / 100)).toFixed(
      2
    );
  }

  // ===>更改为  no2/nox （直接除）
  formDialog.value.no2 =
    (beforeGenerate.no2 / beforeGenerate.nox).toFixed(2) * 100;

  //o
  if (beforeGenerate.ounit != "" && beforeGenerate.quantityFlow != "") {
    // if (beforeGenerate.ounit == "1") {
    //   // 转为Nm3/h
    //   formDialog.value.o = (
    //     (beforeGenerate.o * beforeGenerate.quantityFlow) /
    //     100
    //   ).toFixed(2);
    // }
    if (beforeGenerate.ounit == "3") {
      //Nm3/h 转为mol%
      formDialog.value.o =
        (beforeGenerate.o * 100) / beforeGenerate.quantityFlow.toFixed(2);
    } else if (beforeGenerate.ounit == "2") {
      //kg/h 转为Nm3/h
      formDialog.value.o = ((beforeGenerate.o / 32) * 22.4).toFixed(2);
      //Nm3/h 转为mol%
      formDialog.value.o =
        (beforeGenerate.o * 100) / beforeGenerate.quantityFlow.toFixed(2);
    } else {
      formDialog.value.o = beforeGenerate.o;
    }
  }
  //干基转湿基
  if (beforeGenerate.otype == "1") {
    formDialog.value.o = (formDialog.value.o * (1 - driver)).toFixed(2);
  }

  //co  1-mol%  2-kg/h  3-Nm3/h
  if (beforeGenerate.coUnit != "" && beforeGenerate.quantityFlow != "") {
    if (beforeGenerate.coUnit == "1") {
      //mol% 转为Nm3/h
      formDialog.value.co = (
        (beforeGenerate.co * beforeGenerate.quantityFlow) /
        100
      ).toFixed(2);
    } else if (beforeGenerate.coUnit == "2") {
      //kg/h 转为Nm3/h
      formDialog.value.co = ((beforeGenerate.co / 28) * 22.4).toFixed(2);
    } else {
      formDialog.value.co = beforeGenerate.co;
    }
  }
  //最终转换为 kg/h
  formDialog.value.co = ((formDialog.value.co * 28) / 22.4).toFixed(2);
  //干基转湿基
  if (beforeGenerate.coType == "1") {
    formDialog.value.co = (formDialog.value.co * (1 - driver / 100)).toFixed(2);
  }

  //co2
  if (beforeGenerate.co2Unit != "" && beforeGenerate.quantityFlow != "") {
    // if (beforeGenerate.co2Unit == "1") {
    //   //mol% 转为Nm3/h
    //   formDialog.value.co2 = (
    //     (beforeGenerate.co2 * beforeGenerate.quantityFlow) /
    //     100
    //   ).toFixed(2);
    // }
    if (beforeGenerate.co2Unit == "3") {
      //Nm3/h 转为mol%
      formDialog.value.co2 =
        (beforeGenerate.co2 * 100) / beforeGenerate.quantityFlow.toFixed(2);
    } else if (beforeGenerate.co2Unit == "2") {
      //kg/h 转为Nm3/h
      formDialog.value.co2 = ((beforeGenerate.co2 / 44) * 22.4).toFixed(2);
      //Nm3/h 转为mol%
      formDialog.value.co2 =
        (beforeGenerate.co2 * 100) / beforeGenerate.quantityFlow.toFixed(2);
    } else {
      formDialog.value.co2 = beforeGenerate.co2;
    }
  }
  //干基转湿基
  if (beforeGenerate.co2Type == "1") {
    formDialog.value.co2 = (formDialog.value.co2 * (1 - driver / 100)).toFixed(
      2
    );
  }

  //烟气流量  干基转湿基
  if (beforeGenerate.quantityFlowType == "1") {
    formDialog.value.quantityFlow = (
      formDialog.value.quantityFlow /
      (1 - driver / 100)
    ).toFixed(2);
  }

  // kg/h  转为 Nm3/h
  //Q=Qz/M*22.4
  // M：烟气的摩尔质量
  // M=(氧含量（mol%）*32+水蒸汽含量（mol%）*18+二氧化碳含量（mol%）*44+一氧化碳含量（mol%）*28+氮气（mol%）*28+氩气（mol%）*40+氢气（mol%）*2)/100
  if (beforeGenerate.quantityFlowUnit == "2") {
    const M =
      (formDialog.value.o * 32 +
        formDialog.value.h2o * 18 +
        formDialog.value.co2 * 44 +
        formDialog.value.co * 28 +
        beforeGenerate.n2 * 28 +
        beforeGenerate.ar2 * 40 +
        beforeGenerate.h2 * 2) /
      100;
    formDialog.value.quantityFlow = (
      (formDialog.value.quantityFlow / M) *
      22.4
    ).toFixed(2);
  }

  //第一个弹框的出口氮氧化物排放值(mg/Nm3) 要转换为湿基
  formDialogBefore.value.outNoxDry = (
    formDialogBefore.value.outNox *
    (1 - driver / 100)
  ).toFixed(2);
}

//弹框最终保存
function handleSave() {
  //点保存的时候先把当前的formDialog.value存到saveFormData里面
  commonFilter();
  //过滤掉不填的那些数据

  beforeGenerate();
  //改成只显示当前tab页的
  const computeListChange = [];
  for (let i = 0; i < allBeforeData.value.length; i++) {
    if (allBeforeData.value[i].conditionType == activeName.value) {
      computeListChange.push(allBeforeData.value[i]);
    }
  }
  // const parame = {
  //   projectId: id,
  //   smokeFlow: "1",
  //   catalystsName: "DNX-LD",
  //   categoryName: "939",
  //   reactorCount: 1,
  //   lifetime: 35040,
  //   groupCount: 10,
  //   outNox: 30,
  //   outNh3: 2.5,
  //   k: 0.56984,
  //   k0: 17.51,
  //  // computeList: allBeforeData.value,
  //  computeList: computeListChange,
  // };
  const parame = {
    projectId: id,
    smokeFlow: formDialogBefore.value.smokeFlow,
    catalystsName: formDialogBefore.value.catalystsName,
    categoryName: formDialogBefore.value.categoryName,
    reactorCount: formDialogBefore.value.reactorCount,
    lifetime: formDialogBefore.value.lifetime,
    groupCount: formDialogBefore.value.groupCount,
    outNox: formDialogBefore.value.outNox,
    outNoxDry: formDialogBefore.value.outNoxDry,
    outNh3: formDialogBefore.value.outNh3,
    k: formDialogBefore.value.year,
    reactorL: formDialogBefore.value.reactorL,
    reactorW: formDialogBefore.value.reactorW,
    nh3NoxRatio: formDialogBefore.value.outNh3Nox,
    nh3NoxRatioOffset: formDialogBefore.value.nh3NoxRatioOffset,
    computeList: computeListChange,
  };
  request({
    url: "/system/project/v2/generate",
    method: "post",
    //   data: formDialogBefore.value,
    data: parame,
  }).then((response) => {
    if (response.code == 200) {
      const batchId = response.data;
      ElMessage.success("保存前置条件成功");
      ElMessageBox.confirm(
        "检测到输入条件修改，是否立即开始计算设计方案？",
        "提示",
        {
          confirmButtonText: "立即生成",
          cancelButtonText: "稍后",
          type: "warning",
        }
      )
        .then(() => {
          router.push({
            path: `/projects/projectData/makeProject/${id}/${batchId}`,
            query: {
              reactorL: formDialogBefore.value.reactorL,
              reactorW: formDialogBefore.value.reactorW,
              objectData: JSON.stringify(formDialogBefore.value),
            },
          });
          //  router.push(`/project/makeProject/${id}/${batchId}`);
        })
        .catch(() => {
          getBatchId();
          showDialog.value = false;
        });
    } else {
      ElMessage.error("保存失败");
    }
  });
  // } else {
  //   ElMessage.error("存在未填写的工况，请填写完整后再保存！");
  //   return;
  // }
  // formRefDialog.value.validate((valid) => {
  //   if (valid) {
  //     // const computeList = ref([]);
  //     // computeList.value.push({ ...formDialog.value });
  //     //先把最后一个form加进去
  //     saveFormData.value.push({ ...formDialog.value });
  //     formDialogBefore.value.computeList = saveFormData.value;
  //     // formDialogBefore.value.conditionType = typeValue.value;
  //     // formDialogBefore.value.computeList[0].conditionType = typeValue.value;
  //     // formDialogBefore.value.computeList[0].projectId = id;

  //     request({
  //       url: "/system/project/generate",
  //       method: "post",
  //       data: formDialogBefore.value,
  //     }).then((response) => {
  //       console.log(response);
  //       if (response.code == 200) {
  //         const batchId = response.data;
  //         ElMessage.success("保存前置条件成功");
  //         ElMessageBox.confirm(
  //           "检测到输入条件修改，是否立即开始计算设计方案？",
  //           "提示",
  //           {
  //             confirmButtonText: "立即生成",
  //             cancelButtonText: "稍后",
  //             type: "warning",
  //           }
  //         )
  //           .then(() => {
  //             router.push(`/project/makeProject/${id}/${batchId}`);
  //           })
  //           .catch(() => {
  //             showDialog.value = false;
  //           });
  //       } else {
  //         ElMessage.error("保存失败");
  //       }
  //     });
  //   }
  // });
}

//进入页面的时候先看有没有batchId
function getBatchId() {
  request({
    url: "/system/project/v2/selectBatchIdAndNameListByProjectId/" + id,
    method: "get",
    params: {},
  }).then((response) => {
    if (response.code == 200) {
      allDesign.value = response.data;
    }
  });
}

//找到全部的conditionType 然后存到没一个对象里面
function handleBeforeSaveData() {
  //根据projectid取出全部conditionId
  for (let i = 0; i < tabsData.value.length; i++) {
    let parame = { id: id, name: tabsData.value[i].name };
    request({
      url: "/system/project/v2/getConditionIdByProjectId",
      method: "post",
      data: parame,
    }).then((response) => {
      if (response.code == 200) {
        allBeforeData.value.push({
          conditionType: tabsData.value[i].name,
          projectConditionId: response.data.toString(),
          projectFurnaceId: tabsData.value[i].content.projectFurnaceId,
          quantityFlow: "",
          temperature: "",
          pressure: "",
          nox: "",
          no2: "",
          o: "",
          h2o: "",
          co: "",
          co2: "",
          so2: "",
          so3: "",
          pm: "",
          precondition: "性能保证条件描述",
          remark: "备注，不显示",
        });
      }
    });
  }
}

//最终保存前的校验
function beforeGenerate() {
  const hasIncompleteData = allBeforeData.value.some((item) => {
    // 检查是否至少有一个必填字段有值
    const hasAnyValue = requiredFields.some(
      (field) =>
        item[field] !== "" && item[field] !== null && item[field] !== undefined
    );

    // 如果有值，但必填字段有空值
    return (
      hasAnyValue &&
      requiredFields.some(
        (field) =>
          item[field] === "" ||
          item[field] === null ||
          item[field] === undefined
      )
    );
  });
  return !hasIncompleteData;
}

//删除设计方案
function deleteDetail(itemId, itemName) {
  ElMessageBox.confirm(`是否确认删除设计方案：${itemName}？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      request({
        url: `/system/project/deleteMstnSchemeBatchByBatchId/${itemId}`,
        method: "get",
      }).then((response) => {
        if (response.code == 200) {
          ElMessage.success("删除成功");
          getBatchId();
        } else {
          ElMessage.error("删除失败");
        }
      });
    })
    .catch(() => {});
}

//测试使用 添加占位符
function test() {
  formDialogBefore.value = {
    projectId: id,
    smokeFlow: "0",
    catalystsName: "",
    categoryName: "",
    reactorCount: "",
    lifetime: "",
    groupCount: 10,
    outNox: "",
    outNh3: "",
    k: "",
    k0: "",
    smokeRateOffset: 15,
    smokeTemperatureOffset: 10,
    nh3NoxRatioOffset: 5,
    reactorL: "",
    reactorW: "",
    outNh3: "",
    a: 1,
    b: 1,
  };
  formDialog.value.precondition = "性能保证条件描述";
  formDialog.value.remark = "备注，不显示";
}

//添加设计方案的时候 转换通用单位数据
function translateCommonUnit() {
  //找到当前的那些值
  const sessionData = ref({});
  for (let i = 0; i < formDataOther.value.length; i++) {
    if (formDataOther.value[i].conditionType == currentActiveName.value) {
      sessionData.value = formDataOther.value[i];
      sessionData.value.temperature = formDataOther.value[i].ar3;
      sessionData.value.pressure = formDataOther.value[i].ar4;
      sessionData.value.nox = formDataOther.value[i].ar5;
      sessionData.value.no2 = formDataOther.value[i].ar6;
      sessionData.value.o = formDataOther.value[i].ar7;
      sessionData.value.h2o = formDataOther.value[i].ar8;
      sessionData.value.co = formDataOther.value[i].ar9;
      sessionData.value.co2 = formDataOther.value[i].ar10;
      sessionData.value.so2 = formDataOther.value[i].ar11;
      sessionData.value.so3 = formDataOther.value[i].ar12;
      sessionData.value.pm = formDataOther.value[i].ar13;
      break;
    }
  }
  //烟气流量：
  if (
    sessionData.value.quantityFlow != null &&
    sessionData.value.quantityFlow != undefined
  ) {
  }
  //烟气压力：
  if (
    sessionData.value.pressure != null &&
    sessionData.value.pressure != undefined
  ) {
  }
  //氮氧化物：
  if (sessionData.value.nox != null && sessionData.value.nox != undefined) {
  }
  //二氧化氮：
  if (sessionData.value.no2 != null && sessionData.value.no2 != undefined) {
  }
  //氧含量：
  if (sessionData.value.o != null && sessionData.value.o != undefined) {
  }

  //水蒸气含量：
  if (sessionData.value.h2o != null && sessionData.value.h2o != undefined) {
  }
  //一氧化碳：
  if (sessionData.value.co != null && sessionData.value.co != undefined) {
  }
  //二氧化碳：
  if (sessionData.value.co2 != null && sessionData.value.co2 != undefined) {
  }
  //二氧化硫：
  if (sessionData.value.so2 != null && sessionData.value.so2 != undefined) {
  }
  //三氧化硫：
  if (sessionData.value.so3 != null && sessionData.value.so3 != undefined) {
  }
  console.log(sessionData.value);
}

function designList() {
  router.push(`/projects/projectData/projectDesignList/${id}`).then(() => {});
}

//获取催化剂类型号数据源
function getCategoryNameSource() {
  request({
    url: `/system/project/getCategoryNameSource`,
    method: "get",
  }).then((response) => {
    if (response.code == 200) {
      categoryNameSource.value = response.data;
    }
  });
}

onMounted(() => {
  getList();
  getBatchId();
  getCategoryNameSource();
  test();
  // 接收并解析对象
  if (route.query.objectData) {
    formDialogBefore.value = JSON.parse(route.query.objectData);
  }
  timer = setTimeout(() => {
    handleBeforeSaveData();
  }, 1000);
});

// 组件卸载时清除定时器
onUnmounted(() => {
  clearTimeout(timer);
});
</script>

<style scoped>
.design-center {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
}

.app-bottom {
  width: 100%;
  margin: auto;
  background-color: #f5f5f5;
  font-size: smaller;
  text-align: center;
  line-height: 50px;
}

.headtitle {
  margin-left: 10px;
  font-size: 18px;
}

.app-container {
  padding: 10px;
  height: 100%;
  width: 100%;
}

.body-div {
  height: calc(100% - 20px);
  width: 100%;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow-y: auto;
}

.custom-descriptions {
  width: 97%;
  margin: auto;
  font-size: 15px;
}

.custom-descriptions :deep(.el-descriptions-item) {
  width: 50%; /* 强制每行两列 */
  display: inline-block;
  box-sizing: border-box;
}

:deep(.el-descriptions__label:not(.is-bordered-label)) {
  color: #355af0;
}

:deep(.el-tabs__header) {
  margin: 0;
}

.custom-descriptions .el-descriptions__title {
  padding-left: 10px;
  border-left: 2px solid #409eff;
}

.shuxian {
  height: 23px;
  width: 5px;
  background-color: #355af0;
}

.form-title {
  font-size: 14px;
  font-weight: 400;
  color: #395df0;
}

.form-text {
  font-size: 14px;
  font-weight: 400;
  color: #727272;
}
</style>
